package com.citic.topview.app.mobile.controller;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.citic.topview.app.security.AppUsernamePasswordToken;
import com.citic.topview.app.service.AvoidLoginService;
import com.citic.topview.app.utils.LoginUtil;
import com.citic.topview.common.app.vo.AppVO;
import com.citic.topview.common.bean.Query;
import com.citic.topview.common.system.entity.User;
import com.citic.topview.common.vo.AppResultVO;
import com.citic.topview.common.vo.ResultVO;
import com.citic.topview.system.controller.BaseController;
import com.citic.topview.system.service.UserService;
import com.citic.topview.system.util.ShiroUtils;

@Controller
@RequestMapping("/app/login")
public class AppLoginController extends BaseController{

	private Logger logger = LoggerFactory.getLogger(AppLoginController.class);
	
	@Autowired
    private UserService userService;
	
	@Autowired
	private AvoidLoginService avoidLoginService;
	
	@ResponseBody
	@RequestMapping(value = { "li" })
	public AppResultVO<Object> login(String username, String password, String uniqueId, HttpServletRequest request) {
		//根据用户编号（no），登录名（loginName），手机号（mobile）获取唯一用户
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("loginName", username);
        User user = userService.getByUser(new Query(map));
		if (user == null) {
			return setResult(AppResultVO.ERROR, "用户不存在", null);
		}
		
		// 判断是否跟设备绑定
		try {
			
		} catch (Exception e1) {
			return setResult(AppResultVO.ERROR, "判断是否跟设备绑定时，抛出异常", null);
		}
		
		try {
			Subject subject = SecurityUtils.getSubject();
			if (subject.isAuthenticated()) {
				try {
					LoginUtil.saveAvoidLogin(avoidLoginService, user, username, password, uniqueId);
				} catch (Exception e) {
					logger.error("保存设备登录信息失败", e);
				}
				AppResultVO<Object> result = setResult(AppResultVO.SUCCESS, "already login", null);
				User u = ShiroUtils.getUser();
				result.setBizVO(u);
				return result;
			}
			
			boolean rememberMe = true; 
			String host = request.getRemoteHost();
			String agent = request.getHeader("user-agent").substring(0, request.getHeader("user-agent").indexOf("/"));
			AuthenticationToken token = new AppUsernamePasswordToken(user.getLoginName(), password, rememberMe, host, true, agent);
			subject.login(token); 
		} catch (UnknownAccountException e) {
			return setResult(AppResultVO.ERROR, "用户名或者密码不正确", null);
		} catch (IncorrectCredentialsException e) {
			return setResult(AppResultVO.ERROR, "用户名或者密码不正确", null);
		} catch (AuthenticationException e) {
			return setResult(AppResultVO.ERROR, e.getMessage(), null);
		} catch (Exception e){
			return setResult(AppResultVO.ERROR, "登录出错，请稍后再试", null);
		}
		
		// 保存设备登录信息
		try {
			LoginUtil.saveAvoidLogin(avoidLoginService, user, username, password, uniqueId);
		} catch (Exception e) {
			logger.error("保存设备登录信息失败", e);
		}
		
		AppResultVO<Object> result = setResult(ResultVO.SUCCESS, "login ok", null);
		User u = ShiroUtils.getUser();
		result.setBizVO(u);
		
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = {"checkLogin"})
	public AppResultVO<Object> checkPadLogin(String username, String password, String uniqueId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = ShiroUtils.getUser();
		if (user == null) {
			AppResultVO<Object> result = freeLogin(false, null, request);
	    	if (result == null) {
	    		return setResult(ResultVO.ERROR, "会话已失效，请重新登录!", null);
	    	} else {
	    		return result;
	    	}
		} else {
			if (User.DEL_FLAG_DELETE.equals(user.getDelFlag())) {
				ShiroUtils.logout();
				return setResult(ResultVO.ERROR, "该用户已经被删除，请联系管理员!", null);
			}
			
			AppResultVO<Object> result = setResult(ResultVO.SUCCESS, "login ok", null);
			User u = ShiroUtils.getUser();
			result.setBizVO(u);
			return result;
		}
	}

	// 免登录
	private AppResultVO<Object> freeLogin(boolean b, AppVO appVO, HttpServletRequest request) {

		return null;
	}
}
